package com.feature.core.webmvc;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import com.feature.core.util.TraceIdUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class MDCInteceptor implements AsyncHandlerInterceptor {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private ThreadLocal<Long> stime = new ThreadLocal<Long>();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		try {
			MDC.put("traceId", TraceIdUtil.createTraceID());
			Long startTime = System.currentTimeMillis();
			this.stime.set(startTime);
		} catch (Exception e) {
			this.logger.error("HTTP入口追踪ID 产生过程出现错误", e);
		}

		return true;
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		try {
			logger.info("{}执行时间：{}", request.getRequestURI(), System.currentTimeMillis() - stime.get());
		} catch (Exception e) {
			this.logger.error("HTTP追踪数据推送异常", e);
		}

	}
}
